<!--
 * @Descripttion: appid管理技术后台（测试环境）
 * @version: 
 * @Author: zhangfan
 * @email: 2207044692@qq.com
 * @Date: 2021-04-12 15:27:34
 * @LastEditors: zhangfan
 * @LastEditTime: 2021-05-12 11:32:43
-->
<template>
  <div class="container" ref="mainCon">
    <div class="reminderTop" v-if="topTipShow">
      <i class="el-icon-warning"></i>应用类型维护说明：您所使用的【
      <span style="color: #ff4242"
        >{{ inputInfo.serverName }}{{ inputInfo.version }}</span
      >】版本维护，暂时无法与平台对接，如有问题请与管理员联系。
    </div>
    <topTitle :titleText="`appId管理`"></topTitle>
    <div class="mainCon" :style="{ top: topTipShow ? '104px' : '68px' }">
      <el-row class="searchBox searchInputWidth">
        <el-form :inline="true" :model="filterField" ref="accountForm">
          <el-col :lg="8" :xl="6">
            <el-form-item label="单位名称" class="row-padding-bottom">
              <el-input
                placeholder="请输入"
                clearable
                v-model="filterField.inputName"
              />
            </el-form-item>
          </el-col>
          <el-col :lg="8" :xl="6">
            <el-form-item label="单位类型" class="row-padding-bottom">
              <el-select
                placeholder="请选择"
                v-model="filterField.inputType"
                clearable
              >
                <el-option
                  v-for="(item, index) in inputTypeOption"
                  :key="index"
                  :label="item.name"
                  :value="item.label"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <template v-if="advanced">
            <el-col :lg="8" :xl="6">
              <el-form-item label="appId" class="row-padding-bottom">
                <el-input
                  placeholder="请输入"
                  clearable
                  v-model="filterField.appId"
                />
              </el-form-item>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-form-item label="appId状态" class="row-padding-bottom">
                <el-select
                  placeholder="请选择"
                  v-model="filterField.enabled"
                  clearable
                >
                  <el-option label="启用" value="ENABLED" />
                  <el-option label="停用" value="DISABLE" />
                </el-select>
              </el-form-item>
            </el-col>
          </template>
          <el-form-item>
            <a
              @click="toggleAdvanced"
              style="margin-left: 40px; color: #409eff; cursor: pointer"
              class="btnColor"
            >
              {{ advanced ? '收起' : '展开' }}
              <i
                :class="advanced ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"
              ></i>
            </a>
            <el-button
              type="primary"
              icon="icon iconfont iconchazhao1"
              @click="searchTable"
              class="searchBtn"
            >
              <span>搜索</span>
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button
              v-if="isShowAdd"
              class="commonBut saveBtn funComBut"
              icon="icon iconfont icontianjia"
              @click="addAppid"
            >
              <span class="opetareText">添加</span>
            </el-button>
          </el-form-item>
        </el-form>
      </el-row>
      <div class="spacing"></div>
      <!-- 列表 -->
      <div
        ref="tableBox"
        :class="hiddleToolBar ? 'tableBoxCur tableBox' : 'tableBoxCur'"
      >
        <el-table
          ref="tableBox1"
          :max-height="tableHeight"
          :data="tableData"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          stripe
          v-loading="loading"
          style="border: 1px solid #dfe6ec"
        >
          <el-table-column label="单位名称" width="230">
            <template slot-scope="scope">
              <copyText
                :tableIndex="scope.$index"
                :copyTextName="scope.row.inputName"
                :columnName="'inputName'"
              ></copyText>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="inputTypeName"
            label="单位类型"
            :formatter="formatTd"
            width="150"
          />
          <el-table-column
            align="center"
            prop="enabled"
            label="appID"
            min-width="300"
          >
            <template slot-scope="scope">
              {{ scope.row.appId }}
              <br />
              <el-switch
                class="switch"
                v-model="scope.row.enabled"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-value="ENABLED"
                inactive-value="DISABLE"
                active-text="启用"
                inactive-text="停用"
                @change="changStatus($event, scope.row)"
              >
                >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="appSecret"
            label="appSecret"
            :formatter="formatTd"
            min-width="280"
          />

          <el-table-column
            align="center"
            prop="effectiveEndDate"
            label="有效期"
            width="230"
          >
            <template slot-scope="scope">
              <p
                v-if="
                  scope.row.effectiveEndDate == '4712-12-31' ||
                  scope.row.effectiveEndDate == '4712-12-31 00:00:00'
                "
              >
                长期有效
              </p>
              <p
                v-else-if="currentTime > scope.row.effectiveEndDate"
                style="color: #ff4242"
              >
                {{ scope.row.effectiveEndDate }} (已过期)
              </p>
              <p v-else>
                {{ scope.row.effectiveEndDate }}
              </p>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="操作"
            width="300"
            fixed="right"
          >
            <template slot-scope="scope">
              <div>
                <el-link
                  v-if="isShowUpdate"
                  type="primary"
                  @click="updateRow(scope.row)"
                  >查看详情</el-link
                >
                <el-link
                  v-if="
                    (scope.row.inputType == 'GOV' && isShowUpdate) ||
                    (scope.row.inputType == 'PLAT' && isShowUpdate)
                  "
                  type="primary"
                  @click="designatedItem(scope.row)"
                  >查看项目</el-link
                >
                <el-link
                  v-if="isShowUpdate"
                  type="primary"
                  @click="dockingLog(scope.row)"
                  >对接日志
                </el-link>
              </div>
            </template>
          </el-table-column>
          <!-- 表格数据为空时，页面显示 -->
          <div slot="empty" v-show="isShow">
            <emptyTable emptyText="暂无相关信息" />
          </div>
        </el-table>
        <!-- filterField为搜索条件 -->
        <Pagination
          ref="pagination"
          @getList="getTableList"
          :filterField="filterField"
          :requestUrl="requestUrl"
          @getpageSize="getpageSize"
          @getpageNo="getpageNo"
        />
      </div>
    </div>
  </div>
</template>

<script>
import common from '../../kits/common'
import scrollTable from '@/mixin/scrollTable.js'

export default {
  name: 'equipmentAppidJsCs',
  mixins: [scrollTable],
  data() {
    return {
      advanced: false,
      topTipShow: false, //enabled 启用显示  DISABLE 禁用不显示顶部
      inputInfo: {},
      requestUrl: 'api-m/inputUserAuth/base/v1/page', //表格请求路径
      loading: false,
      departmentTypeFun: '正式环境',
      isShow: false,
      tableData: [], //表格数据
      inputTypeOption: [
        {
          name: '工程项目',
          label: 'PROJECT',
        },
        {
          name: '施工企业',
          label: 'CONSTRUCTOR',
        },
        {
          name: '第三方平台',
          label: 'PLAT',
        },
        {
          name: '政府部门',
          label: 'GOV',
        },
      ], //表格数据
      filterField: {
        inputName: '',
        inputType: '',
        appId: '',
        enabled: '',
      },
      currentTime: '', //当前时间
      pageSize: 20,
      pageNo: 1,
      companyList: [], //项目名称下来列表
      pageSizeNumber: 20,
      total: 0,
      pageNo: 1,
      companyId: '',
      addOrEdit: '',
      formVisible: false,
      formData: {
        id: '',
        companyId: '',
        companyName: '',
        pointId: '',
        type: '',
        machineNo: '',
        direction: '',
        authCode: '',
        remark: '',
      },
      formRules: {
        companyId: [
          { required: true, message: '项目名称不能为空', trigger: 'change' },
        ],
        type: [
          { required: true, message: '设备类型不能为空', trigger: 'change' },
        ],
        machineNo: [
          { required: true, message: '请输入正确的识别号', trigger: 'blur' },
        ],
        authCode: [
          { required: true, message: '授权码不能为空', trigger: 'blur' },
        ],
        direction: [
          { required: true, message: '进出方向不能为空', trigger: 'change' },
        ],
      },
      isRuleLoading: false,
      isDisabled: false,
      usccDisabled: false,
      id: '',
      typeData: '',
      companyNameUscc: '', //修改赋值的uscc
      projectNameId: '', //修改赋值的projectId
      zkIsShow: false,
      points: [], //工点列表
      isShowAdd: '',
      isShowUpdate: '',
    }
  },
  created() {
    this.getCurrentTime()
    //获取环境，名称，版本号
    this.getInputUserServer()
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
    })
    this.isShowAdd =
      this.$store.state.buttonLimitsArr.indexOf('testAppIdManageJS:add') > -1
    this.isShowUpdate =
      this.$store.state.buttonLimitsArr.indexOf('testAppIdManageJS:update') > -1
  },
  activated() {
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData(this.pageNo, this.pageSize)
    })
  },
  methods: {
    toggleAdvanced() {
      this.advanced = !this.advanced
    },
    getInputUserServer() {
      this.axios({
        method: 'post',
        url: 'api-m/inputUserServer/base/v1/list',
        data: {
          userId: this.$store.state.userId,
        },
      })
        .then((response) => {
          if (!response.data.hasError) {
            this.inputInfo = response.data.result[0] || {}
            //enabled 启用显示  DISABLE 禁用不显示顶部
            // this.topTipShow =
            //   this.inputInfo.enabled == "ENABLED" ? false : true;
          } else {
            this.$message({
              type: 'error',
              message: response.data.errorMsg,
            })
          }
        })
        .catch((error) => {
          this.$message.error('数据获取失败')
        })
    },
    getCurrentTime() {
      var now = new Date()
      var year = now.getFullYear()
      var month = now.getMonth() + 1
      var day = now.getDate()
      var time = year + '-' + common.pad(month) + '-' + common.pad(day)
      this.currentTime = time
    },
    /**
     * @description: 切换状态
     * @param {*} index
     * @param {*} row
     */
    changStatus($event, row) {
      const vm = this
      if (row.enabled == 'ENABLED') {
        const h = this.$createElement
        this.$msgbox({
          title: '提示',
          message: h('p', null, [
            h('span', null, '此操作将'),
            h('span', { style: 'color: #98F203' }, '启用'),
            h('span', '该appId?, 是否继续?'),
          ]),
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              let id = row.id
              let enable = 'ENABLED'
              this.changAppidStatus(id, enable)
              done()
            } else {
              this.$refs.pagination.getTableListData()
              done()
            }
          },
        }).then((action) => {})
      } else {
        const h = this.$createElement
        this.$msgbox({
          title: '提示',
          message: h('p', null, [
            h('span', null, '此操作将'),
            h('span', { style: 'color: #FF4949' }, '停用'),
            h('span', '该appId, 是否继续?'),
          ]),
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              let id = row.id
              let enable = 'DISABLE'
              this.changAppidStatus(id, enable)
              done()
            } else {
              this.$refs.pagination.getTableListData()
              done()
            }
          },
        }).then((action) => {})
      }
    },
    /**
     * @description: 切换appid管理的状态
     */
    changAppidStatus(id, enable) {
      this.axios({
        method: 'post',
        data: { id: id, enable: enable },
        url: 'api-m/inputUserAuth/base/v1/enable',
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.$refs.pagination.getTableListData()
              this.$message({
                message: '修改成功',
                type: 'success',
              })
            } else {
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    getpageSize(val) {
      this.pageSize = val
    },
    getpageNo(val) {
      this.pageNo = val
    },
    /**
     * @description: 添加appID
     * @param {*} data
     */
    addAppid() {
      this.$router.push({
        path: '/home/interfacePlatform/addAppid',
        name: 'addAppid',
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/interfacePlatform/equipmentAppidJsCs',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    getTableList(data) {
      this.tableData = data
      this.loading = false
      if (this.tableData.length < 1) {
        this.isShow = true
      }
    },
    //加载项目列表
    getCompanyList() {
      this.axios({
        method: 'post',
        url: 'api-att/nc/attrule/expand/findcomp',
      })
        .then(
          (response) => {
            if (!response.data.hasError) {
              this.companyList = response.data.result
            }
          },
          (response) => {}
        )
        .catch((error) => {})
    },
    selectChange(val) {},
    handleSizeChange(val) {},
    handleCurrentChange(val) {
      this.getCompanyList(val, this.pageSizeNumber, this.companyId)
    },
    //列表查询
    searchTable() {
      this.$refs.pagination.getTableListData()
    },
    //查看详情
    updateRow(row) {
      this.$router.push({
        path: '/home/interfacePlatform/equipmentAppidDetailJs',
        name: 'equipmentAppidDetailJs',
        query: {
          id: row.id,
          appId: row.appId,
          typePage: 'jscs',
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/interfacePlatform/equipmentAppidJsCs',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    //查看项目
    designatedItem(row) {
      this.$router.push({
        path: '/home/interfacePlatform/designatedItemJs',
        name: 'designatedItemJs',
        query: {
          authId: row.id,
          typePage: 'jscs',
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/interfacePlatform/equipmentAppidJsCs',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
    //对接日志
    dockingLog(row) {
      this.$router.push({
        path: '/home/interfacePlatform/dockingLog',
        name: 'dockingLog',
        query: {
          appId: row.appId,
          type: 'jscs',
          page: 'home',
        },
      })
      this.$store.commit('CHANGE_SLIDER_NAME', {
        oldUrl: '/home/interfacePlatform/equipmentAppidJsCs',
        newUrl: this.$router.currentRoute.fullPath,
      })
    },
  },
}
</script>

<style scoped lang="less">
.container {
  .reminderTop {
    color: #666;
    font-size: 14px;
    background: #fffbe6;
    line-height: 36px;
    border-radius: 3px;
    padding: 0 24px;
    // margin: 24px 24px 0 24px;
    i {
      color: #ffaa00;
      margin-right: 4px;
      font-size: 20px;
      vertical-align: -2px;
    }
  }
  .selectWidth {
    width: 100%;
  }
}
/deep/ .el-tag {
  line-height: 23px;
  height: 23px;
}

/* switch按钮样式 */
/deep/.switch .el-switch__label {
  position: absolute;
  display: none;
  color: #fff !important;
}
/*打开时文字位置设置*/
/deep/.switch .el-switch__label--right {
  z-index: 1;
}
/* 调整打开时文字的显示位子 */
/deep/.switch .el-switch__label--right span {
  margin-right: 9px;
}
/*关闭时文字位置设置*/
/deep/.switch .el-switch__label--left {
  z-index: 1;
}
/* 调整关闭时文字的显示位子 */
/deep/.switch .el-switch__label--left span {
  margin-left: 9px;
}
/*显示文字*/
/deep/.switch .el-switch__label.is-active {
  display: block;
}
/* 调整按钮的宽度 */
/deep/.switch.el-switch .el-switch__core,
/deep/.el-switch .el-switch__label {
  width: 70px !important;
  margin: 0;
}
@import '../../../static/css/filterArea.less';
</style>
